// 手写events模块
function EventEmitter(){
    this.events = {} // 保存所有事件监听函数
}
// 给指定事件绑定事件处理函数
EventEmitter.prototype.on = EventEmitter.prototype.addListener = function(type, listener){
    if(this.events[type]){
        if(this._maxListeners!=0 && this.events[type].length >= this._maxListeners){
            console.error("maxListeners")
        }
        this.events[type].push(listener)
    }else{
        this.events[type] = [listener]
    }
}


EventEmitter.prototype.listeners = function(event){
    return this.events[event]
}


EventEmitter.prototype.once = function(type, listener){
    let wrapper = (...rest) => {
        listener.apply(this, rest)
        this.removeListener(type, wrapper)
    }
    this.on(type, wrapper)
}


EventEmitter.prototype.removeListener = function(type, listener){
    if(this.events[type]){
        this.events[type] = this.events[type].filter(l => l!=listener)
    }
}
// 移除某个事件的所有监听函数
EventEmitter.prototype.removeAllListener = function(type){
    delete this.events[type]
}


EventEmitter.prototype.emit = function(type, ...rest){
    this.events[type] && this.events[type].forEach(listener => listener.apply(this, rest))
}

module.exports = EventEmitter




